package com.dfrz.problem.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Session;

import com.dfrz.problem.dao.RoleDao;
import com.dfrz.problem.model.Role;


public class RoleDaoImpl implements RoleDao{
	private static final Logger logger = LoggerFactory
			.getLogger(RoleDaoImpl.class);

	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	
	//新增角色
	@Override
	public boolean addRole(Role role) {
		if(role == null){
			return false;
		}
		getSession().save(role);
		logger.debug("新增角色:{} " + role.getRoleName());
		return true;
	}
	
	
	//获取角色信息
	public Role getRole(int roleId) {
		String hql = "FROM Role e WHERE e.roleId =:roleId";
		Query query = getSession().createQuery(hql);
		query.setParameter("roleId", roleId);
		Role role = (Role) query.uniqueResult();
		if (role != null) {
			logger.debug("Role -----> {}", role.getRoleId());
		}
		return role;
	}
	
	@Override
	public Role getRole(String restring) {
		// TODO Auto-generated method stub
		
		String hql = "FROM Role e WHERE e.roleName =:roleName";
		Query query = getSession().createQuery(hql);
		query.setParameter("roleName", restring);
		Role role = (Role) query.uniqueResult();
		if (role != null) {
			logger.debug("Role -----> {}", role.getRoleName());
		}
		return role;
	}
	
	//删除角色
	public boolean deleteRole(String roleId) {
		
		//判断角色是否存在
		String hql = "FROM role e WHERE e.roleId =:"+roleId;
		Query query1 = getSession().createQuery(hql);

		query1.setParameter("roleId", roleId);
		Role reRole = (Role) query1.uniqueResult();
		if (reRole == null) {
			logger.debug("角色{}删除失败，该角色不存在！", roleId);
			return false;
		}else {
			String hql2 = "delete Role e where e.roleId =:"+roleId;
			Query query = getSession().createQuery(hql2);
			query.setParameter("roleId", roleId);
			query.executeUpdate();
			return true;
		}			
	}
	
	//返回全部角色
	@SuppressWarnings("unchecked")
	public List<Role> roleList() {
		List<Role> roles = new ArrayList<Role>();
		String hql = "from Role ";
		Query query = getSession().createQuery(hql);
		roles = query.list();
		return roles;
	}

	@Override
	public Boolean updateRole(Role role) {
		// TODO Auto-generated method stub
		getSession().update(role);
		logger.debug("角色:{} 修改成功" + role.getRoleName());
		return true;
	}

	public void createRole(){
		if(getSession().createQuery("FROM Role").list().size() == 0){
			getSession().save(new Role(1,"未分配","系统默认角色",new Date()));
			logger.debug("创建默认的系统角色...");
		}
	}
}
